package com.code.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.code.common.constant.CodeConst;
import com.code.common.exception.ServiceException;
import com.code.common.model.ResponseCode;
import com.code.user.model.RoleDO;
import com.code.user.mapper.RoleMapper;
import com.code.user.model.RolePermissionDO;
import com.code.user.model.UserRoleDO;
import com.code.user.service.RolePermissionService;
import com.code.user.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.user.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author Yan
 * @since 2023-04-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleDO> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public void bindNormalRoleByUserId(String userId) {
        LambdaQueryWrapper<RoleDO> wrapper = new LambdaQueryWrapper<RoleDO>().eq(RoleDO::getName, RoleService.NORMAL_ROLE);
        RoleDO role = this.getOne(wrapper);

        if (StrUtil.isEmptyIfStr(role)) {
            throw new ServiceException(ResponseCode.SERVER_ERROR);
        }

        UserRoleDO userRoleDO = new UserRoleDO();
        userRoleDO.setRid(role.getId());
        userRoleDO.setUid(userId);
        userRoleService.save(userRoleDO);
    }

    @Override
    public List<RoleDO> searchRoleByUid(String uid) {
        return this.baseMapper.searchRoleByUid(uid);
    }

    @CacheEvict(key = CodeConst.ROLE_PERMISSION_HASH_KEY)
    @Override
    public boolean bindPermission(String rid, String pid) {
        RolePermissionDO rolePermissionDO = new RolePermissionDO();
        rolePermissionDO.setRid(rid);
        rolePermissionDO.setPid(pid);
        return rolePermissionService.save(rolePermissionDO);
    }

    @CacheEvict(key = CodeConst.ROLE_PERMISSION_HASH_KEY)
    @Override
    public boolean unbindPermission(String rid, String pid) {
        LambdaQueryWrapper<RolePermissionDO> wrapper = new LambdaQueryWrapper<RolePermissionDO>().eq(RolePermissionDO::getRid, rid).eq(RolePermissionDO::getPid, pid);
        return rolePermissionService.remove(wrapper);
    }
}
